/**
 * Created : Mar 23, 2012
 *
 * @author pquiring
 */

import java.awt.*;
import java.io.*;
import javaforce.*;
import javax.swing.*;

public class OptionsDialog extends javax.swing.JDialog {

  /**
   * Creates new form OptionsDialog
   */
  public OptionsDialog(java.awt.Frame parent, boolean modal, XML xml, XML.XMLTag options) {
    super(parent, modal);
    initComponents();
    setPosition();
    this.xml = xml;
    this.options = options;
    XML.XMLTag tag;
    tag = xml.getTag(new String[] {"jfburn", "options", "boot"});
    if (tag != null) {
      if (tag.content.equals("true")) enableBoot.setSelected(true);
    }
    tag = xml.getTag(new String[] {"jfburn", "options", "bootType"});
    if (tag != null) {
      int idx = JF.atoi(tag.content);
      if ((idx >= 0) && (idx <= 3)) bootType.setSelectedIndex(idx);
    }
    tag = xml.getTag(new String[] {"jfburn", "options", "bootFile"});
    if (tag != null) {
      bootFile.setText(tag.content);
    }
    listDevices();
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        enableBoot = new javax.swing.JCheckBox();
        bootType = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        bootFile = new javax.swing.JTextField();
        selectBootFile = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        devs = new javax.swing.JComboBox();
        extractFromDrive = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        extractFromImage = new javax.swing.JButton();
        accept = new javax.swing.JButton();
        cancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Options");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Boot"));

        enableBoot.setText("Make Disc Bootable");

        bootType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Floppy Disk", "Hard Drive", "No Emulation" }));

        jLabel1.setText("Image Type");

        jLabel2.setText("File");

        selectBootFile.setText("Select...");
        selectBootFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectBootFileActionPerformed(evt);
            }
        });

        jLabel3.setText("Extract From Drive");

        extractFromDrive.setText("Extract");
        extractFromDrive.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                extractFromDriveActionPerformed(evt);
            }
        });

        jLabel4.setText("Extract From Image");

        extractFromImage.setText("Extract");
        extractFromImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                extractFromImageActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(enableBoot)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bootType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bootFile))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(devs, 0, 196, Short.MAX_VALUE)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(extractFromImage)
                                        .addGap(0, 0, Short.MAX_VALUE)))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(selectBootFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(extractFromDrive, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(enableBoot)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bootType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(bootFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(selectBootFile))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(devs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(extractFromDrive))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(extractFromImage))
                .addContainerGap(35, Short.MAX_VALUE))
        );

        accept.setText("Accept");
        accept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                acceptActionPerformed(evt);
            }
        });

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(cancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(accept)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(accept)
                    .addComponent(cancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

  private void acceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acceptActionPerformed
    xml.addSetTag(options, "boot", "", "" + enableBoot.isSelected());
    xml.addSetTag(options, "bootType", "", "" + bootType.getSelectedIndex());
    xml.addSetTag(options, "bootFile", "", bootFile.getText());
    dispose();
  }//GEN-LAST:event_acceptActionPerformed

  private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
    dispose();
  }//GEN-LAST:event_cancelActionPerformed

  private void selectBootFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectBootFileActionPerformed
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(false);
    File path = new File(JF.getUserPath() + "/jfburn");
    path.mkdirs();
    chooser.setCurrentDirectory(path);
    if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
    String filename = chooser.getSelectedFile().getAbsolutePath();
    bootFile.setText(filename);
  }//GEN-LAST:event_selectBootFileActionPerformed

  private void extractFromDriveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_extractFromDriveActionPerformed
    extractFromDrive();
  }//GEN-LAST:event_extractFromDriveActionPerformed

  private void extractFromImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_extractFromImageActionPerformed
    extractFromISO();
  }//GEN-LAST:event_extractFromImageActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton accept;
    private javax.swing.JTextField bootFile;
    private javax.swing.JComboBox bootType;
    private javax.swing.JButton cancel;
    private javax.swing.JComboBox devs;
    private javax.swing.JCheckBox enableBoot;
    private javax.swing.JButton extractFromDrive;
    private javax.swing.JButton extractFromImage;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton selectBootFile;
    // End of variables declaration//GEN-END:variables

  private XML xml;
  private XML.XMLTag options;

  private void listDevices() {
    devs.removeAllItems();
    File file = new File("/dev/");
    File files[] = file.listFiles(new FileFilter() {
      public boolean accept(File file) {
        if (file.getName().startsWith("sr")) return true;
        return false;
      }
    });
    for(int a=0;a<files.length;a++) {
      devs.addItem(files[a].getAbsolutePath());
    }
  }

  private void extractFromDrive() {
    if (devs.getSelectedIndex() == -1) return;
    String dev = (String)devs.getSelectedItem();
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(false);
    File path = new File(JF.getUserPath());
    chooser.setCurrentDirectory(path);
    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
    String filename = chooser.getSelectedFile().getAbsolutePath();
    ShellProcess sp = new ShellProcess();
    String cmd[] = {"geteltorito", "-o", filename, dev};
    String output = sp.run(cmd, false);
    if (output==null) {
      JFAWT.showError("Error", "Error occured");
    } else {
      JFAWT.showMessage("Notice", "Boot Image extracted");
    }
  }

  private void extractFromISO() {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(false);
    File path = new File(JF.getUserPath());
    chooser.setCurrentDirectory(path);
    chooser.setDialogTitle("Select ISO Image file");
    if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
    String image = chooser.getSelectedFile().getAbsolutePath();

    chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(false);
    chooser.setCurrentDirectory(path);
    chooser.setDialogTitle("Save to boot image file");
    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
    String filename = chooser.getSelectedFile().getAbsolutePath();

    ShellProcess sp = new ShellProcess();
    String cmd[] = {"geteltorito", "-o", filename, image};
    String output = sp.run(cmd, false);
    if (output==null) {
      JFAWT.showError("Error", "Error occured");
    } else {
      JFAWT.showMessage("Notice", "Boot Image extracted");
    }
  }
  private void setPosition() {
    Rectangle s = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
    Dimension d = getPreferredSize();
    setLocation(s.width/2 - d.width/2, s.height/2 - (d.height/2));
  }
}
